package org.jeecg.modules.third.digitalseal.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @Description: Image和Base64转换
 * @author: luruirui
 * @date: 2021年04月19日 17:33
 */
public class ImageBase64Util {
    static BASE64Encoder encoder = new BASE64Encoder();
    static BASE64Decoder decoder = new BASE64Decoder();

    public static String getImageBinary(String filePath, String imgType) {
        File f = new File(filePath);
        try {
            BufferedImage bi = ImageIO.read(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, imgType, baos);
            byte[] bytes = baos.toByteArray();

            return encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean base64StringToImage(String base64String, String outPath) {
        if (base64String == null || base64String.equals("")) // 图像数据为空
            return false;
        try {
            //解决后台接收base64编码出现空格的问题,核心问题
            //String base64Str = base64String.replace(" ", "+");
            // Base64解码
            String[] split = base64String.split(",");
            String base64Str = split[1];
            byte[] bytes = new BASE64Decoder().decodeBuffer(base64Str);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            //生成图片
//            OutputStream out = new FileOutputStream(outPath);
//            out.write(bytes);
//            out.flush();
//            out.close();

            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            BufferedImage image  = ImageIO.read(bais);
            File file = new File(outPath);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            ImageIO.write(image , "png", file);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
